/*
 * Copyright (C) 2014 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { socket } from "@kit.NetworkKit"
import { IllegalArgumentException } from "./Error/error"

/**
 * Versions of TLS that can be offered when negotiating a secure socket. See
 * [javax.net.ssl.SSLSocket.setEnabledProtocols].
 */
export class TlsVersion {
  javaName: string

  constructor(javaName: string) {
    this.javaName = javaName
  }

  toString(): string {
    return this.javaName
  }

  /**
   * Returns the TlsVersion instance for the given protocol name.
   * @param javaName - The protocol name (e.g., "TLSv1.3", "TLSv1.2")
   * @returns The corresponding TlsVersion instance
   * @throws Error if the protocol name is not recognized
   */
  static forJavaName(javaName: string): TlsVersion {
    switch (javaName) {
      case "TLSv1.3":
        return TlsVersion.TLS_1_3
      case "TLSv1.2":
        return TlsVersion.TLS_1_2
      case "TLSv1.1":
        return TlsVersion.TLS_1_1
      case "TLSv1":
        return TlsVersion.TLS_1_0
      case "SSLv3":
        return TlsVersion.SSL_3_0
      default:
        throw new IllegalArgumentException("Unexpected TLS version: " + javaName)
    }
  }

  /**
   * Converts TLS version name to HarmonyOS socket.Protocol.
   * Note: HarmonyOS socket.Protocol only supports TLSv1.2 and TLSv1.3.
   * @param name - The protocol name (e.g., "TLSv1.3", "TLSv1.2")
   * @returns The corresponding socket.Protocol
   * @throws Error if the protocol is not supported by OpenHarmony
   */
  static forNameWithProtocol(name: string): socket.Protocol {
    switch (name) {
      case "TLSv1.3":
        return socket.Protocol.TLSv13
      case "TLSv1.2":
        return socket.Protocol.TLSv12
      default:
        throw new IllegalArgumentException(`Unsupported protocol for OpenHarmony: ${name}. Only TLSv1.2 and TLSv1.3 are supported.`)
    }
  }

  static TLS_1_3 = new TlsVersion("TLSv1.3")
  static TLS_1_2 = new TlsVersion("TLSv1.2")
  static TLS_1_1 = new TlsVersion("TLSv1.1")
  static TLS_1_0 = new TlsVersion("TLSv1")
  static SSL_3_0 = new TlsVersion("SSLv3")

}